document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const modal = document.getElementById('modal');
    const modalTitle = document.getElementById('modalTitle');
    const modalCourseCode = document.getElementById('modalCourseCode');
    const modalCourseName = document.getElementById('modalCourseName');
    const modalCourseType = document.getElementById('modalCourseType');
    const modalDepartment = document.getElementById('modalDepartment');
    const modalTeacher = document.getElementById('modalTeacher');
    const modalTime = document.getElementById('modalTime');
    const modalLocation = document.getElementById('modalLocation');
    const modalDescription = document.getElementById('modalDescription');
    const closeModalBtn = document.getElementById('closeModal');
    const courseTableBody = document.getElementById('courseTableBody');
    // const searchForm = document.getElementById('courseSearchForm');

    // 检查关键元素
    if (!modal || !courseTableBody) {
        showToast('页面加载错误：关键元素缺失', 'error');
        return;
    }

    // 创建toast容器
    createToastContainer();

    // 为所有查看按钮添加点击事件
    courseTableBody.addEventListener('click', async function(e) {
        if (e.target.closest('.view-btn')) {
            const row = e.target.closest('tr');
            if (!row) return;

            const courseId = row.getAttribute('data-course-id');
            if (!courseId) {
                showToast('课程ID缺失，无法获取详情', 'error');
                return;
            }

            try {
                // 发送AJAX请求获取课程详情
                const response = await fetch(`/teacher/course/${courseId}/detail`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码：${response.status}`);
                }

                const courseData = await response.json();

                // 填充模态框数据
                modalTitle.textContent = `课程详情: ${courseData.course_name}`;
                modalCourseCode.textContent = courseData.course_code;
                modalCourseName.textContent = courseData.course_name;
                modalCourseType.textContent = courseData.credit ? `${courseData.credit}学分` : '未设置';
                modalDepartment.textContent = courseData.department;
                modalTeacher.textContent = courseData.teacher;
                modalTime.textContent = courseData.time || '未安排';
                modalLocation.textContent = courseData.location || '未指定';
                modalDescription.textContent = courseData.description || '暂无描述';

                // 显示模态框
                openModal();
                showToast(`成功加载课程 "${courseData.course_name}" 详情`, 'success');
            } catch (error) {
                console.error('获取课程详情失败:', error);
                showToast('获取课程详情失败，请重试', 'error');
            }
        }
    });

    // 关闭模态框
    closeModalBtn?.addEventListener('click', closeModal);

    // 点击模态框外部关闭
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeModal();
        }
    });

    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && !modal.classList.contains('pointer-events-none')) {
            closeModal();
        }
    });

    // 打开模态框函数
    function openModal() {
        modal.classList.remove('opacity-0', 'pointer-events-none');
        modal.querySelector('div').classList.remove('scale-95');
        modal.querySelector('div').classList.add('scale-100');
        document.body.style.overflow = 'hidden';
    }

    // 关闭模态框函数
    function closeModal() {
        modal.classList.add('opacity-0', 'pointer-events-none');
        modal.querySelector('div').classList.remove('scale-100');
        modal.querySelector('div').classList.add('scale-95');
        document.body.style.overflow = '';
    }

    // 创建toast容器
    function createToastContainer() {
        const toastContainer = document.createElement('div');
        toastContainer.id = 'toastContainer';
        toastContainer.className = 'fixed top-4 right-4 z-50 flex flex-col gap-3 w-80 max-w-full';
        document.body.appendChild(toastContainer);
    }

    // 显示toast消息
    function showToast(message, type = 'info', duration = 3000) {
        const toastContainer = document.getElementById('toastContainer');
        if (!toastContainer) return;

        // 创建toast元素
        const toast = document.createElement('div');

        // 设置toast样式
        const bgColors = {
            success: 'bg-green-50 border-l-4 border-green-400',
            error: 'bg-red-50 border-l-4 border-red-400',
            warning: 'bg-yellow-50 border-l-4 border-yellow-400',
            info: 'bg-blue-50 border-l-4 border-blue-400'
        };

        const iconClasses = {
            success: 'fa-check-circle text-green-500',
            error: 'fa-times-circle text-red-500',
            warning: 'fa-exclamation-triangle text-yellow-500',
            info: 'fa-info-circle text-blue-500'
        };

        toast.className = `${bgColors[type] || bgColors.info} p-4 rounded shadow-lg transform transition-all duration-300 opacity-0 translate-y-2`;
        toast.innerHTML = `
            <div class="flex items-start">
                <div class="flex-shrink-0 pt-0.5">
                    <i class="fa ${iconClasses[type] || iconClasses.info}"></i>
                </div>
                <div class="ml-3 flex-1">
                    <p class="text-sm font-medium text-gray-800">${message}</p>
                </div>
                <button class="ml-2 flex-shrink-0 text-gray-400 hover:text-gray-600 focus:outline-none">
                    <i class="fa fa-times"></i>
                </button>
            </div>
        `;

        // 添加到容器
        toastContainer.appendChild(toast);

        // 显示动画
        setTimeout(() => {
            toast.classList.remove('opacity-0', 'translate-y-2');
            toast.classList.add('opacity-100', 'translate-y-0');
        }, 10);

        // 自动关闭
        const closeToast = () => {
            toast.classList.remove('opacity-100', 'translate-y-0');
            toast.classList.add('opacity-0', 'translate-y-2');
            setTimeout(() => {
                toast.remove();
            }, 300);
        };

        // 设置定时器
        const timeoutId = setTimeout(closeToast, duration);

        // 点击关闭按钮
        const closeBtn = toast.querySelector('button');
        closeBtn.addEventListener('click', () => {
            clearTimeout(timeoutId);
            closeToast();
        });
    }
});